package cn.connorma.example.oauth.github.handlers;

import cn.connorma.example.oauth.github.ExampleServerMain;
import cn.connorma.example.oauth.github.RestHandler;
import cn.connorma.example.oauth.github.Result;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

/**
 * github oauth请求code回调处理
 * 用户允许github授权时，github回调服务端地址回传code，服务器使用code、clientId、clientSecret向github申请access token
 *
 * @author matian
 * @date 2023-02-13 15:38:44
 */
public class LoginCallBackRestHandler implements RestHandler {

    private static final Gson GSON = new Gson();

    @Override
    public Result handle(HttpServerRequest request) {
        String code = request.getParam("code");

        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("client_id", ExampleServerMain.CLIENT_ID);
        params.put("client_secret", ExampleServerMain.CLIENT_KEY);
        HttpResponse response = HttpUtil.createPost("https://github.com/login/oauth/access_token")
                .header(Header.ACCEPT, ContentType.JSON.getValue())
                .body(GSON.toJson(params))
                .execute();
        int status = response.getStatus();
        if (status >= 200 && status < 300) {
            String content = response.body();
            Map<String, String> map = GSON.fromJson(content, Map.class);
            System.out.println("request access token: " + map);
            return requestUserInfo(map.get("token_type"), map.get("access_token"));
        } else {
            System.out.println("request access token error:" + status + ", " + response.body());
            return Result.error(500).msg("request access token error");
        }
    }

    /**
     * 使用github access token获取用户信息
     *
     * @param tokenType
     * @param accessToken
     * @return
     */
    private Result requestUserInfo(String tokenType, String accessToken) {
        System.out.println("requestUserInfo:" + tokenType + ", " + accessToken);
        HttpResponse response = HttpUtil.createGet("https://api.github.com/user")
                .header("Authorization", tokenType + " " + accessToken)
                .execute();
        int status = response.getStatus();
        if (status >= 200 && status < 300) {
            String content = response.body();
            return Result.success().data(content);
        } else {
            System.out.println("request github user info error:" + status + ", " + response.body());
            return Result.error(500).msg("request github user info error");
        }
    }
}
